const axios = require("axios").default.create({
  headers: {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36",
    'accept-language': 'zh-CN,zh;q=0.9',
  }
});
const rn = require("random-number");

const FALLBACK_URL = "https://m.tuniucdn.com/fb2/t1/G6/M00/0F/2F/Cii-U1231YaIYF0bAATwh87Hl1AAACDegAtvacABPCf334.jpg"

/**
 * @returns {Promise<String>}
 */
function getImageUrl() {
  return new Promise(resolve => {
    axios.get(`https://trips.tuniu.com/travels/index/ajax-list?sortType=1&page=${rn({
      integer: true,
      min: 1,
      max: 9
    })}&limit=10&_=1640843295655`, {
      headers: {
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'referer': ' https://trips.tuniu.com/',
        // 'sec-ch-ua': '"Chromium";v="96", "Opera";v="82", ";Not A Brand";v="99"',
        // 'sec-ch-ua-mobile': '?0',
        // 'sec-ch-ua-platform': '"Windows"',
        // 'sec-fetch-dest': 'empty',
        // 'sec-fetch-mode': 'cors',
        // 'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest'
      }
    }).then(axresp => {
      if (axresp.data
        && axresp.data.data
        && axresp.data.data.rows
        && axresp.data.data.rows.length) {
        let M = axresp.data.data.rows.length;
        let i = rn({ integer: true, min: 0, max: M - 1 });
        let item = axresp.data.data.rows[i];
        let picUrl = String(item.picUrl);
        if (picUrl) {
          if (picUrl.endsWith('imageView2/2/w/400/h/300')) {
            return resolve(picUrl.replace('imageView2/2/w/400/h/300', "imageView2/2/w/1000"))
          }
          if (picUrl.endsWith('imageMogr2%2Fthumbnail%2F1360x%2Fstrip%2Fquality%2F90')) {
            return resolve(picUrl.replace('imageMogr2%2Fthumbnail%2F1360x%2Fstrip%2Fquality%2F90', "imageView2/2/w/1000"))
          }
          return resolve(picUrl);
        }
      }
      throw new Error();
      debugger
    }).catch(err => {
      resolve(FALLBACK_URL);
    })
  })
}


module.exports = {
  getImageUrl
}